package cn.com.dhcc.turbo.service.monitor.gather;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.handler.modulehandler.valuebean.BetweenValue;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.util.UUIDGenerator;
import cn.com.dhcc.app.pub.core.consts.AppConst;
import cn.com.dhcc.turbo.entity.monitor.QuotaValueOnTime;
import cn.com.dhcc.turbo.entity.registry.AdapterInfo;
import cn.com.dhcc.turbo.entity.registry.NodeInfo;
import cn.com.dhcc.turbo.service.exch.cmdata.RecvCmDataService;
import cn.com.dhcc.turbo.service.exch.cmdata.SendCmDataService;
import cn.com.dhcc.turbo.service.monitor.MonitorService;
import cn.com.dhcc.turbo.service.monitor.QUOTA;
import cn.com.dhcc.turbo.service.registry.AdapterInfoService;
import cn.com.dhcc.turbo.service.registry.NodeInfoService;

/**
 * 常规数据监控统计指标
 */
@Service
public class CmDataPerHourGatherService {

	@SuppressWarnings("deprecation")
	Logger logger = Log.getExistLogger(Log.LOGTYPE.MONITOR);
	@Autowired
	private SendCmDataService sendCmDataService;
	@Autowired
	private RecvCmDataService recvCmDataService;
	@Autowired
	NodeInfoService nodeInfoService;

	@Autowired
	MonitorService monitorService;
	@Autowired
	QuotaGatherUtil quotaGatherUtil;
	@Autowired
	AdapterInfoService adapterService;

	/**
	 * 按系统计算每小时发送量
	 */
	public void cmStructuredSendFlowHourForAdapter() {
		QUOTA quota = QUOTA.STRUCTURED_SEND_FLOW_HOUR_FOR_ADAPTER;
		int num = 0;
		logger.info("开始收集指标[" + quota.getDesc() + "]...");
		try {
			List<AdapterInfo> adapterList = adapterService.getLocalAdapterList();
			Date now = new Date();
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(now);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.set(Calendar.MILLISECOND, 0);
			Date begintime = calendar.getTime();
			calendar.add(Calendar.HOUR, 1);
			Date endtime = calendar.getTime();

			for (AdapterInfo adapter : adapterList) {
				String code = adapter.getAdapterCode();
				WhereCondition searchData = new WhereCondition();
				searchData
						.where()
						.eq("data_type", AppConst.ExchDataType.CM_DATA.value())
						.and()
						.eq("send_status", AppConst.SendStatus.SENT.value())
						.and()
						.eq("send_adaptorcode", code)
						.and()
						.between("created",
								new BetweenValue(begintime, endtime));
				num = sendCmDataService.count(searchData);
				QuotaValueOnTime onTime = new QuotaValueOnTime();
				onTime.setQuotaCode(quota.getCode());
				onTime.setMtime(now);
				onTime.setId(UUIDGenerator.getUUID());
				onTime.setStatus(QuotaValueOnTime.QuotaHadlerStatus.WAIT_HANDLER
						.getCode());
				onTime.setOwnerId(adapter.getId());
				onTime.setCurrentValue1("" + num);
				monitorService.insertQuotaOnTime(onTime);
			}
		} catch (ServiceException e) {
			logger.error("指标[" + quota.getDesc() + "]值收集失败", e);
		}
		logger.info("指标[" + quota.getDesc() + "]值收集结束，值为：" + num);
	}

	/**
	 * 按系统计算每小时接收量
	 */
	public void cmStructuredRecvFlowHourForAdapter() {
		QUOTA quota = QUOTA.STRUCTURED_RECV_FLOW_HOUR_FOR_ADAPTER;
		int num = 0;
		logger.info("开始收集指标[" + quota.getDesc() + "]...");
		try {
			List<AdapterInfo> adapterList = adapterService.getLocalAdapterList();
			Date now = new Date();
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(now);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.set(Calendar.MILLISECOND, 0);
			Date begintime = calendar.getTime();
			calendar.add(Calendar.HOUR, 1);
			Date endtime = calendar.getTime();

			for (AdapterInfo adapter : adapterList) {
				String code = adapter.getAdapterCode();
				WhereCondition searchData = new WhereCondition();
				searchData
						.where()
						.eq("data_type", AppConst.ExchDataType.CM_DATA.value())
						.and()
						.eq("send_status", AppConst.SendStatus.SENT.value())
						.and()
						.eq("send_adaptorcode", code)
						.and()
						.between("created",
								new BetweenValue(begintime, endtime));
				num = recvCmDataService.count(searchData);
				QuotaValueOnTime onTime = new QuotaValueOnTime();
				onTime.setQuotaCode(quota.getCode());
				onTime.setMtime(now);
				onTime.setId(UUIDGenerator.getUUID());
				onTime.setStatus(QuotaValueOnTime.QuotaHadlerStatus.WAIT_HANDLER
						.getCode());
				onTime.setOwnerId(adapter.getId());
				onTime.setCurrentValue1("" + num);
				monitorService.insertQuotaOnTime(onTime);
			}
		} catch (ServiceException e) {
			logger.error("指标[" + quota.getDesc() + "]值收集失败", e);
		}
		logger.info("指标[" + quota.getDesc() + "]值收集结束，值为：" + num);
	}
	/**
     * 在收集完系统监控值后执行
     */
	public void autoGatherNodeAndDomainOntimeValue() {
		QUOTA sysQuotas[] = { 
				QUOTA.STRUCTURED_SEND_FLOW_HOUR_FOR_ADAPTER,
				QUOTA.STRUCTURED_RECV_FLOW_HOUR_FOR_ADAPTER
				};
		try {
			NodeInfo localNode = nodeInfoService.getLocalNode();
			if(localNode==null){
				logger.error("自动根据系统指标值计算节点指标指标失败:节点未初始化");
				return;
			}
			quotaGatherUtil.gatherValueForNodeByAdapterLastValue(sysQuotas);
			quotaGatherUtil.gatherValueForDomainByAdapterLastValue(sysQuotas);
		} catch (ServiceException e) {
			logger.error("自动计算指标值失败!", e);
		}
	}
}
